#include "GLWindow.h"

using namespace std;
using namespace Shiny::Maths;
using namespace Shiny::Timing;

namespace
{
	Vector2 verts[] = 
	{
		Vector2(0.0f, 0.1f),
		Vector2(-0.1f, -0.1f),
		Vector2(0.1f, -0.1f),
	};

	Vector2 shipPosition(-1.0f, -1.0f);

}

void Shiny::Editor::GLWindow::initializeGL()
{

	GLenum errorCode = glewInit();
	assert(errorCode == 0);
	


	glGenBuffers(1, &vertexBufferID);
	glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID);

	glBufferData(GL_ARRAY_BUFFER, sizeof(verts),
		NULL, GL_DYNAMIC_DRAW);

	/*
	myGlList = glGenLists(1);
	glNewList(myGlList, GL_COMPILE);
		glEnableClientState(GL_VERTEX_ARRAY);
		glVertexPointer(2, GL_FLOAT, 0, verts);
		glDrawArrays(GL_TRIANGLES, 0, 6);
	glEndList();
	*/

	connect(&timer, SIGNAL(timeout()), this, SLOT(frameUpdate() ));
	timer.start(0);

}

void Shiny::Editor::GLWindow::paintGL()
{

	

	glClear(GL_COLOR_BUFFER_BIT);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);


	static const unsigned int NUM_VERTS = sizeof(verts) / sizeof(*verts);

	Vector2 translatedVerts[NUM_VERTS];
	for (unsigned int i = 0; i < NUM_VERTS; i++)
	{
		translatedVerts[i] = verts[i] + shipPosition;
	}
	glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(translatedVerts), translatedVerts);


	glDrawArrays(GL_TRIANGLES, 0, 3);
	/*
	glCallList(myGlList);
	*/
}

void Shiny::Editor::GLWindow::frameUpdate()
{
	clock.Update(); // Inform the clock of the new frame event

	Vector2 velocity(0.5f, 0.5f);
	float gte = clock.GetTimeElapsed();

	shipPosition = shipPosition + velocity * gte;

	repaint();

}

bool Shiny::Editor::GLWindow::Shutdown()
{
	return clock.Shutdown();
}

bool Shiny::Editor::GLWindow::Initialise()
{
	return clock.Initialise();
}